package com.paradogs.framework.core.utils;

import com.paradogs.framework.core.exceptions.GlobalExceptionDispatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * @author: yumi
 * @date: 2023/11/16  13:32
 * @Description: TODO
 */
@Slf4j
public class PRAsync {

    private static AsyncTaskExecutor taskExecutor;

    @Autowired
    public void setServerProperties(AsyncTaskExecutor taskExecutor) {
        PRAsync.taskExecutor = taskExecutor;
    }


    public static <T> CompletableFuture<T> supply(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier, taskExecutor).exceptionally(e -> {
            SpringUtils.getBean(GlobalExceptionDispatch.class).forward(e); // 转发到全局异常
            throw new RuntimeException(e); // 中断回调
        });
    }

    public static CompletableFuture run(Runnable runnable) {
        return CompletableFuture.runAsync(runnable, taskExecutor);
    }

}
